package com.wctj.api.base.utils;


import com.wctj.api.base.dto.JwtUserDTO;

import java.util.HashMap;
import java.util.Map;

public class UserContext {

    private static final ThreadLocal<JwtUserDTO> CONTEXT = new ThreadLocal<JwtUserDTO>();

    private UserContext() {
    }

    /**
     * 获取用户信息
     *
     */
    public static JwtUserDTO getLoginUser() {
        return CONTEXT.get();
    }

    /**
     * 存放用户信息
     *
     */
    public static void setLoginUser(JwtUserDTO user) {
        CONTEXT.set(user);
    }

    /**
     * 清除当前线程内引用，防止内存泄漏
     */
    public static void remove() {
        CONTEXT.remove();
    }


    public static void setContextUserWithFeignHeader(JwtUserDTO currentUser) {
//        if (Objects.isNull(currentUser.getGroupId())) {
//            currentUser.setGroupId(0L);
//        }
        Map<String, String> feignHeader = new HashMap<>();
//        feignHeader.put(JwtConstant.HEADER_NAME_JWT, "abc");
//        feignHeader.put(JwtConstant.HEADER_NAME_USERNAME, currentUser.getUsername());
//        try {
//            feignHeader.put(JwtConstant.HEADER_NAME_REAL_NAME, URLEncoder.encode(currentUser.getRealName(), StandardCharsets.UTF_8.name()));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        feignHeader.put(JwtConstant.HEADER_NAME_TENANT_ID, String.valueOf(currentUser.getTenantId()));
//        feignHeader.put(JwtConstant.HEADER_NAME_USER_ID, String.valueOf(currentUser.getUserId()));
//        feignHeader.put(JwtConstant.HEADER_NAME_GROUP_ID, String.valueOf(currentUser.getGroupId()));
//        feignHeader.put(JwtConstant.HEADER_NAME_IDS_GROUP_ID, currentUser.getIdsGroupId());
//        feignHeader.put(JwtConstant.HEADER_NAME_USER_TYPE, String.valueOf(currentUser.getUserType()));
//        feignHeader.put("X-tmy-userIP", RequestContext.getUserIP());
//        feignHeader.put(JwtConstant.HEADER_NAME_SYSTEM_CODE, "TMY");
//        FeignHeaderHelper.HEADER_CONTEXT.set(feignHeader);

        CONTEXT.set(currentUser);
    }

    public static void removeContextUserWithFeignHeader() {
        CONTEXT.remove();
//        FeignHeaderHelper.HEADER_CONTEXT.remove();
    }

}
